<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :showBack="true">
  </pageHeader>
  <div class="search-main">
    <a-input-group>
      <span> 生产任务编号：</span>
      <a-input v-model="data.code" disabled :style="{ flex: 5 }" />
    </a-input-group>
    <div style="margin-left: 20px; display: flex; align-items: center">
      <span>剩余数量：</span>
      <a-input-number
        :min="1"
        v-model="remaining"
        disabled
        :style="{ flex: 5 }"
      />
    </div>
    <div style="margin-left: 20px; display: flex; align-items: center">
      <span>容量：</span>
      <a-input-number
        :min="1"
        v-model="addData.capacity"
        :max="remaining"
        :style="{ flex: 5 }"
      />
    </div>
    <div style="margin-left: 20px; display: flex; align-items: center">
      <span>张数：</span>
      <a-input-number :min="1" v-model="addData.number" :style="{ flex: 5 }" />
    </div>
    <a-button
      type="primary"
      style="color: aliceblue; margin: 0 20px"
      @click="add"
    >
      <template #icon><icon-qrcode size="18" /> </template>
      <template #default> <span>生成</span> </template>
    </a-button>
  </div>
  <TableTurn :table-data="getData" ref="tableRef">
    <a-table-column :width="70" align="center">
      <template #title> 序号 </template>
      <template #cell="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </a-table-column>
    <a-table-column
      :width="160"
      align="center"
      title="流转卡编码"
      data-index="code"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="生产任务单号"
      data-index="planProduceNumber"
    >
      <template #cell="{ record }">
        {{ record?.produceTask?.code }}
      </template>
    </a-table-column>
    <a-table-column :width="150" align="center" title="关联生产工单">
      <template #cell="{ record }">
        {{ record?.produceTask?.planModel?.workOrderModel?.workCode }}
      </template>
    </a-table-column>
    <a-table-column :width="150" align="center" title="物料编码">
      <template #cell="{ record }">
        {{
          record?.produceTask?.planModel?.workOrderModel?.product
            ?.managementNumber
        }}
      </template>
    </a-table-column>
    <a-table-column :width="150" align="center" title="物料名称">
      <template #cell="{ record }">
        {{
          record?.produceTask?.planModel?.workOrderModel?.product
            ?.managementName
        }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="规格型号"
      data-index="batchCode"
    >
      <template #cell="{ record }">
        {{
          record?.produceTask?.planModel?.workOrderModel?.product
            ?.managementSpec
        }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="标准容量"
      data-index="capacity"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="任务数量"
      data-index="planTaskNumber"
    >
      <template #cell="{ record }">
        {{ record?.produceTask?.planTaskNumber }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="创建人"
      data-index="creatorName"
    >
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="创建时间"
      data-index="createdAt"
    >
      <template #cell="{ record }">
        {{ `${dayjs(record.createdAt).format('YYYY-MM-DD')}` }}
      </template>
    </a-table-column>
    <a-table-column
      :width="150"
      align="center"
      title="操作"
      data-index="remark"
    >
      <template #cell="{ record }">
        <a-button @click="jumpPreview(record.id)" type="text">预览</a-button>
      </template>
    </a-table-column>
  </TableTurn>
</template>

<script setup lang="ts">
  import { reactive, ref, onBeforeUnmount, computed } from 'vue';
  import pageHeader from '@/components/page-header/index.vue';
  import {
    GetFlowCard,
    PostFlowCards,
  } from '@/api/produce-management/produce-list/index';
  import dayjs from 'dayjs';
  import { Message } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const tableRef = ref();

  const title: string = '流程卡设置';
  const breadCrumb: string[] = ['生产管理', '生产计划'];
  const data = reactive(JSON.parse(localStorage.getItem('taskData') as string));
  const addData = reactive({ capacity: 0, number: 0 });
  const remaining = ref(0);
  // 获取表格数据
  const getData = async (pageData?: any) => {
    try {
      const res = await GetFlowCard({ ...pageData, taskId: data.id });
      const res1 = await GetFlowCard({ page: 1, size: -1, taskId: data.id });
      remaining.value = res1.content.reduce(
        (accumulator: number, currentValue: any) => {
          return (
            accumulator - (currentValue.capacity ? currentValue.capacity : 0)
          );
        },
        data.planTaskNumber
      );
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const add = async () => {
    const { number, capacity } = addData;
    if (!number || !capacity) {
      Message.error('容量或张数不能为0');
    }
    const sum = number * capacity;
    if (number && sum <= remaining.value) {
      const flowCards = [];
      const { name: creatorName, id: creatorId } = JSON.parse(
        sessionStorage.getItem('loginInfo') as string
      );
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < number; i++) {
        flowCards.push({
          creatorName,
          taskId: data.id,
          creatorId,
          capacity,
        });
      }
      await PostFlowCards({ flowCards });
      addData.capacity = 0;
      addData.number = 0;
      tableRef.value.loadData();
    } else if (sum > remaining.value) {
      Message.error('生成流程卡容量大于任务数量');
    } else {
      Message.error('生成流程卡数量不能为0');
    }
  };
  const jumpPreview = (id: number) => {
    router.push({
      name: 'FlowCardPreview',
      query: { id: JSON.stringify(id) },
    });
  };
  // onBeforeUnmount(() => {
  //   localStorage.removeItem('taskData');
  // });
</script>

<style lang="less" scoped>
  .search-main {
    display: flex;
    margin: 18px 0 20px 0;
  }
  :deep(.arco-btn-icon) {
    height: 18px;
  }
</style>
